$(function () {
    $('#sendDate').datepicker({ language:'zh-CN', format:'yyyy-mm-dd'} );
});

//确认、重置仓库
$("#wh-confirm-btn").on('click', function () {
    if ($(this).text() == '确认') {
        confirmFlg = 1;
        if ($('#warehouseId').val() == '') {
            $.jBox.tip('请选择仓库');
            return;
        }
        $('#warehouseId').attr('disabled', 'true').css('color', '#ccc');
        $(this).text('重置');
    } else {
        dateFlg = 1;
        confirmFlg = 0;
        selectData = {};
        tempData = {};
        $('#table_list tbody').html('');
        $('#warehouseId').removeAttr('disabled').css('color', '');
        $(this).text('确认');
    }
});

$('#shopId').on('change', function () {
    var shopName = $(this).find('option:selected').text();
    var address = $(this).find('option:selected').attr('info');
    $('#address').html(shopName + ' - ' + address);
});

//修改订货数量
$('#table_list').on('blur', 'input[name=orderQty]', function () {
    var orderQty = $(this).val(),
        storeFlg = $(this).attr('data-Flg');
    if (orderQty == '' || orderQty == 0) {
        orderQty = 0;
        $.jBox.tip('请输入订货数量');
    }
    if (!$.isNumeric(orderQty)) {
        orderQty = 0;
        $(this).val('');
        $.jBox.tip('请输入正确的订货数量');
    }
    var _tr = $(this).parents('tr');
    if(storeFlg == '0'){
        _tr.find('span[name=deliverQty]').html(orderQty);
    }
    selectData[_tr.attr('data-code')]['orderQty'] = orderQty;
});

//初始化物料modal
$('#show-materiel-btn').on('click', function () {
    if(!confirmFlg){
        $.jBox.tip('请确认仓库');
        return;
    }
    $('#add-materiel-modal').modal('show');
    if(mDataTable){
        if(dateFlg){
            mDataTable.ajax.reload();
            dateFlg= 0;
        }
        return;
    }

    mDataTable = $('#search_list').DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'../static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/stock/get-materiel-list',
            type:'post',
            data:function(d){
                d.warehouseId = $('#warehouseId').val();
                d.searchKey = $('#searchKey').val();
            },
            error:getError
        },
        aoColumns: [
            { "data": "id", "bSortable": false },
            { "data": "materielCode", "bSortable": false },
            { "data": "materielName", "bSortable": false },
            { "data": "warehouseName", "bSortable": false },
            { "data": "specDesc", "bSortable": false },
            { "data": "packDesc", "bSortable": false },
            { "data": "purchaseUnit", "bSortable": true },
            { "data": "orderUnit", "bSortable":false },
            { "data": "id", "bSortable":false },
        ],
        columnDefs: [
            {
                "targets": [-1],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                    var orderQty = '';
                    if (!$.isEmptyObject(selectData[data])) {
                        orderQty = selectData[data].orderQty;
                    }
                    var html = '<input name="storeFlg" type="hidden" value="' + full.storeFlg + '">';
                    html += '<input type="text" name="orderQty" value="' + orderQty + '" style="width: 60px" data-id="' + data + '">';
                    return html;
                }
            }
        ],
    });
});

//modal 搜索按钮
$('#search-btn').on('click', function () {
    if(mDataTable) {
        mDataTable.ajax.reload();
    }
});

//modal 选中/取消 checkbox
$('#search_list').on('blur', 'input[name=orderQty]', function () {
    var orderQty = $(this).val();
    var materielId = $(this).attr('data-id');
    if (orderQty != '' && !$.isNumeric(orderQty)) {
        $.jBox.tip('请输入正确的订货数量');
        return;
    }
    if ((orderQty == '' || orderQty == 0) && $.isEmptyObject(selectData[materielId])) {
        return;
    }
    if (!$.isEmptyObject(selectData[materielId]) && selectData[materielId].orderQty == orderQty) {
        return;
    }
    var _tr = $(this).parents('tr');
    tempData[materielId] = {
        materielId: materielId,
        materielCode: _tr.find('td').eq(1).html(),
        materielName: _tr.find('td').eq(2).html(),
        warehouseName: _tr.find('td').eq(3).html(),
        orderQty: orderQty,
        storeFlg:_tr.find('input[name=storeFlg]').val(),
        batch: {}
    }
});

//modal 添加按钮 - 物料
$('#add-materiel-btn').on('click',function () {

    //var postData = [];
    var html = '';
    $.each(tempData, function (i, v) {
        if ($.isEmptyObject(selectData[i])) {
            selectData[i] = v;
        } else {
            if (v.orderQty == '' || v.orderQty == 0) {
                $("#table_list").find('tr[data-code="' + i + '"]').remove();
                delete selectData[i];
                return true;
            }
            selectData[i]['orderQty'] = v['orderQty'];
            $("#table_list").find('tr[data-code="' + i + '"]').remove();
        }
        var devQty = v['storeFlg'] == '1' ? 0 : v['orderQty'];
        html += '<tr data-code="' + i + '">';
        html += '   <td>' + v['materielId'] + '</td>';
        html += '   <td>' + v['materielCode'] + '</td>';
        html += '   <td>' + v['materielName'] + '</td>';
        html += '   <td>' + v['warehouseName'] + '</td>';
        html += '   <td><input class="depart-input" type="text" name="orderQty" data-Flg="' + v['storeFlg'] + '" style="width:80px; height: 22px" value="' + v['orderQty'] + '"></td>';
        html += '   <td><span name="deliverQty">' + devQty + '</span></td>';
        html += '    <td>';
        if (v['storeFlg'] == '1') {
            //postData.push(v);
            html += '<a name="match-stock">【匹配库存】</a>&nbsp;&nbsp;';
        }
        html += '<a name="del-materiel">【删除】</a></td>';
        html += '</tr>';
    });

    $('#add-materiel-modal').modal('hide');
    if (html == '') return;

    dateFlg = 1;
    tempData = {}; //清空临时数据
    $('#table_list tbody').append(html);
    $('#add-materiel-modal').modal('hide');

    //editby lfl 0802 增加批量匹配，取消以下逻辑
    //自动匹配库存
    // if(postData.length){
    //     $.post('/bill/match-stock', {'warehouseId': $('#warehouseId').val(), 'materielData': postData},
    //         function (o) {
    //             if (o.code == 200) {
    //                 if(o.data){
    //                     $.each(o.data, function (i, v) {
    //                         if(!selectData[i]['batch']) selectData[i]['batch'] = {};
    //                         selectData[i]['batch'][v.id] = {
    //                             stockId: v.id,
    //                             batch: v.batch,
    //                             price: v.price,
    //                             deliverQty: v.deliverQty
    //                         };
    //                         $("#table_list").find('tr[data-code="' + i + '"]').find('span[name=deliverQty]').html(v.deliverQty);
    //                     });
    //                 }
    //             } else {
    //                 $.jBox.error(o.val, '错误');
    //             }
    //         },
    //         'json'
    //     );
    // }
});

//匹配库存
$(document).on('click','a[name=match-stock]',function () {
    var _tr = $(this).parents('tr'),
        orderQty = _tr.find('input[name=orderQty]').val();
    if (orderQty == '' || orderQty == 0) {
        $.jBox.tip('请填写订货数量');
        return;
    } else if (!$.isNumeric(orderQty)) {
        $.jBox.tip('请填写正确的订货数量');
        return;
    }
    currCode = _tr.attr('data-code');

    $('#add-stock-modal').modal('show');
    if(sDataTable){
        sDataTable.ajax.reload();
        return;
    }
    sDataTable = $('#search_stock_list').DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'../static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        "ordering": false,
        ajax:{
            url:'/stock/get-materiel-stock',
            type:'post',
            data:function(d){
                d.warehouseId = $('#warehouseId').val();
                d.materielId = currCode;
                d.can_Frozen = 1;
                d.qtyFlg = 1;
            },
            error:getError
        },
        aoColumns: [
            { "data": "materielId"},
            { "data": "materielCode"},
            { "data": "warehouseName"},
            { "data": "supplierName"},
            { "data": "batch"},
            { "data": "price"},
            { "data": "total"},
            { "data": "freeze"},
            { "data": "qty"},
            { "data": "materielId"}
        ],
        columnDefs: [
            {
                "targets": [-1],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                    var deliverQty = 0;
                    if(!$.isEmptyObject(selectData[full.materielId]) && !$.isEmptyObject(selectData[full.materielId]['batch'][full.id])){
                        deliverQty = selectData[full.materielId]['batch'][full.id].deliverQty;
                    }
                    return '<input name="deliverQty" style="width: 50px" value="'+deliverQty+'">' +
                        '<input type="hidden" value="'+ full.id +'" name="stockId">';
                }
            },
            {
                "targets": [-2],
                "orderable": false,
                "searchable": false,
                "render": function (data, type, full) {
                    if (parseInt(data) == 0) {
                        return '<span style="color: red">' + data + '</span>';
                    }
                    return data;
                }
            }
        ]
    });
});

//选择批次
$('#add-stock-btn').on('click', function () {
    var errMsg = '',
        deliverCnt = 0,
        batchData = {},
        tempSup = '',
        supFlg = 0;
    $.each($('#search_stock_list>tbody>tr'), function (i, v) {
        var stockId = $(v).find('input[name=stockId]').val(),
            deliverQty = $(v).find('input[name=deliverQty]').val(),
            batch = $(v).find('td').eq(4).html(),
            supplierName = $(v).find('td').eq(3).html(),
            price = $(v).find('td').eq(5).html();
        if (deliverQty && !$.isNumeric(deliverQty)) {
            errMsg = '请输入正确的发货数量';
            return false;
        }
        if ($.isEmptyObject(selectData[currCode])) {
            errMsg = '数据异常，请刷新页面后重试';
            return false;
        }
        if (deliverQty > 0) {
            batchData[stockId] = {
                stockId: stockId,
                batch: batch,
                price: price,
                deliverQty: deliverQty,
            };
            deliverCnt += parseFloat(deliverQty);
            if(tempSup !='' && tempSup != supplierName && !supFlg){
                supFlg = 1;
            }
            tempSup = supplierName;
        }
    });
    if (errMsg) {
        $.jBox.tip(errMsg);
        return;
    }

    if ($.isEmptyObject(batchData)) {
        $.jBox.tip('请填写发货数据');
        return;
    }

    if(supFlg) {
        $.jBox.confirm("选择物料批次有不同供应商", "是否继续？", function (v) {
            if (v == 'ok') {
                doConfirm(batchData, deliverCnt);
            } else {
                $.jBox.close();
            }
        });
    }else{
        doConfirm(batchData, deliverCnt);
    }
});
function doConfirm(batchData, deliverCnt) {
    selectData[currCode]['batch'] = batchData;
    var spCnt = $('#table_list').find('tr[data-code="' + currCode + '"]').find('span[name=deliverQty]');
    if (deliverCnt != selectData[currCode]['orderQty']) {
        spCnt.css('color', 'red');
    } else {
        spCnt.css('color', '');
    }
    spCnt.html(deliverCnt);
    $('#add-stock-modal').modal('hide');
}

//删除事件
$(document).on('click','a[name=del-materiel]',function () {
    var _tr = $(this).parents('tr');
    delete selectData[_tr.attr('data-code')];
    _tr.remove();
});

//查看图片
$(document).on('click','a[name=show-img]',function () {
    var billNo = $("#billNo").val(),
        materielId = $(this).parents('tr').attr('data-code');

    $('#dtlImgBox').empty();
    $.post('/bill/get-bill-img', {billNo: billNo, materielId: materielId},
        function (o) {
            if (o.code == 200) {
                if(o.data){
                    $.each(o.data['img'], function (i, v) {
                        $('#dtlImgBox').append('<img src="'+v+'" style="width: 500px; margin: 5px">');
                    })
                }
                $('#show-img-modal').modal('show');
            } else {
                $.jBox.error(o.val, '错误');
            }
        },
        'json'
    );
});

//提交事件
function saveRevise() {
    if ($("#warehouseId").val() == '') {
        $.jBox.tip('请选择仓库');
        return;
    }
    if ($("#shopId").val() == '') {
        $.jBox.tip('请选择门店');
        return;
    }
    if ($.isEmptyObject(selectData)) {
        $.jBox.tip('请添加物料信息');
        return;
    }
    if ($("#sendDate").val() == '') {
        $.jBox.tip('请选择发货日期');
        return;
    }

    var stockData = {
        billNo: $("#billNo").val(),
        warehouseId: $("#warehouseId").val(),
        shopId: $("#shopId").val(),
        address: $("#address").html(),
        remark: $("#remark").val(),
        sendDate: $("#sendDate").val(),
        materiels: selectData
    };

    var errMsg = '', tipFlg = 0;
    $.each(selectData, function (i, v) {
        if (!v.orderQty) {
            errMsg = '请填写[' + v.materielName + ']的订货数量';
            return false;
        }
        if(v['storeFlg']=='0') return true;

        if (!v.hasOwnProperty('batch') || $.isEmptyObject(v['batch'])) {
            errMsg = '[' + v.materielName + ']未匹配批次';
            return false;
        }
        var deliverCnt = 0;
        $.each(v['batch'], function () {
            deliverCnt += parseFloat(this.deliverQty);
        });
        if(deliverCnt == 0){
            errMsg = '[' + v.materielName + ']未匹配批次';
            return false;
        }

        if (deliverCnt != v.orderQty) {
            tipFlg = 1;
            errMsg += '[' + v.materielName + ']发货货量不符<br>';
        }
    });

    if (errMsg) {
        if (tipFlg) {
            $.jBox.confirm(errMsg, "是否继续？", function (v) {
                if (v == 'ok') {
                    doSaveBill(stockData);
                } else {
                    $.jBox.close();
                }
            });
        } else {
            $.jBox.tip(errMsg);
            return;
        }
    }else{
        doSaveBill(stockData);
    }
}
function doSaveBill(stockData) {
    $.post('/bill/save-bill', stockData,
        function (data) {
            if (data.code == 200) {
                $.jBox.tip('保存成功', 'success');
                window.setTimeout(function () {
                    history.back();
                }, 1000);
            } else {
                $.jBox.error(data.val, '错误');
            }
        },
        'json'
    );
}